<script lang="ts" setup>
import { ref, reactive } from 'vue';
import {
  ElCard,
  ElButton,
  ElDialog,
  ElInput,
  ElMessage,
  ElMessageBox
} from 'element-plus';
import { usePromptStore } from '../stores/promptStore';
import { type PromptElement, type PromptElementGroup } from '../stores/promps';

const promptStore = usePromptStore();

// 对话框状态
const showDialog = ref(false);
const dialogMode = ref<'create' | 'edit'>('create');
const editingGroupId = ref('');

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  elements: [] as PromptElement[]
});

// 当前编辑的元素
const currentElement = reactive<PromptElement>({
  name_cn: '',
  name_en: '',
  description: ''
});

// 打开创建对话框
const openCreateDialog = () => {
  dialogMode.value = 'create';
  editingGroupId.value = '';
  resetForm();
  showDialog.value = true;
};

// 打开编辑对话框
const openEditDialog = (group: PromptElementGroup) => {
  dialogMode.value = 'edit';
  editingGroupId.value = group.id;
  formData.name = group.name;
  formData.description = group.description || '';
  formData.elements = [...group.elements];
  showDialog.value = true;
};

// 重置表单
const resetForm = () => {
  formData.name = '';
  formData.description = '';
  formData.elements = [];
  resetElementForm();
};

// 重置元素表单
const resetElementForm = () => {
  currentElement.name_cn = '';
  currentElement.name_en = '';
  currentElement.description = '';
};

// 添加元素到表单
const addElement = () => {
  if (currentElement.name_cn && currentElement.name_en) {
    formData.elements.push({ ...currentElement });
    resetElementForm();
  } else {
    ElMessage.warning('请填写元素的中英文名称');
  }
};

// 从表单中删除元素
const removeElement = (index: number) => {
  formData.elements.splice(index, 1);
};

// 保存组
const saveGroup = () => {
  if (!formData.name.trim()) {
    ElMessage.warning('请输入组名称');
    return;
  }

  if (formData.elements.length === 0) {
    ElMessage.warning('请至少添加一个要素');
    return;
  }

  const groupData = {
    name: formData.name,
    description: formData.description,
    elements: formData.elements
  };

  if (dialogMode.value === 'create') {
    promptStore.addGroup(groupData);
    ElMessage.success('要素组创建成功');
  } else {
    promptStore.updateGroup(editingGroupId.value, groupData);
    ElMessage.success('要素组更新成功');
  }

  showDialog.value = false;
};

// 删除组（带确认）
const deleteGroup = async (groupId: string, groupName: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除要素组"${groupName}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    promptStore.deleteGroup(groupId);
    ElMessage.success('要素组删除成功');
  } catch {
    // 用户取消删除
  }
};
</script>

<template>
  <div class="group-manager">
    <!-- 组列表 -->
    <div class="group-list">
      <ElCard v-for="group in promptStore.groups" :key="group.id" class="group-card" shadow="hover">
        <template #header>
          <div class="group-header">
            <div class="group-name">
              <h3>{{ group.name }}</h3>
              <div class="group-actions">
                <ElButton size="small" @click="openEditDialog(group)">
                  编辑
                </ElButton>
                <ElButton size="small" type="danger" @click="deleteGroup(group.id, group.name)"
                  :disabled="promptStore.groups.length <= 1">
                  删除
                </ElButton>
              </div>
            </div>
            <p class="group-description" v-if="group.description">{{ group.description }}</p>
          </div>
        </template>
        <div class="element-tags">
          <el-tag type="primary" v-for="(element, index) in group.elements" :key="index">{{ element.name_cn }}({{
            element.name_en }})</el-tag>
        </div>
      </ElCard>
    </div>

    <!-- 新建组按钮 -->
    <div class="create-button-container">
      <ElButton type="primary" @click="openCreateDialog" style="width: 100%;">
        新建要素组
      </ElButton>
    </div>

    <!-- 创建/编辑组对话框 -->
    <ElDialog fullscreen v-model="showDialog" :title="dialogMode === 'create' ? '新建要素组' : '编辑要素组'" width="600px">
      <div class="dialog-form">
        <div class="form-section">
          <label>组名称</label>
          <ElInput v-model="formData.name" placeholder="请输入组名称" />
        </div>

        <div class="form-section">
          <label>组描述（可选）</label>
          <ElInput v-model="formData.description" type="textarea" :rows="2" placeholder="请输入组描述" />
        </div>

        <div class="form-section">
          <label>要素列表</label>

          <!-- 添加要素表单 -->
          <div class="element-form">
            <div class="element-inputs">
              <ElInput v-model="currentElement.name_cn" placeholder="中文名称" style="margin-bottom: 8px;" />
              <ElInput v-model="currentElement.name_en" placeholder="英文名称" style="margin-bottom: 8px;" />
              <ElInput v-model="currentElement.description" type="textarea" :rows="2" placeholder="要素描述" />
            </div>

            <ElButton type="primary" size="small" @click="addElement" style="margin-top: 8px;">
              添加要素
            </ElButton>
          </div>

          <!-- 要素列表 -->
          <div class="elements-list">
            <div v-for="(element, index) in formData.elements" :key="index" class="element-item">
              <span class="element-names">
                {{ element.name_cn }} ({{ element.name_en }})
              </span>
              <ElButton type="danger" size="small" @click="removeElement(index)">
                删除
              </ElButton>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <ElButton @click="showDialog = false">取消</ElButton>
        <ElButton type="primary" @click="saveGroup">保存</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.group-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 12px;
}

.group-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.group-card {
  margin-bottom: 0;
}

.group-header {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: flex-start;
}

.group-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.group-name {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}

.default-badge {
  background: #67c23a;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.group-description {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}
.element-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.group-elements-count {
  margin: 0 0 12px 0;
  font-size: 12px;
  color: #999;
}

.group-actions {
  display: flex;
  gap: 8px;
}

.create-button-container {
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.dialog-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-section label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.element-form {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background: #f8f9fa;
}

.element-inputs {
  margin-bottom: 8px;
}

.elements-list {
  margin-top: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.element-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  background: white;
}

.element-names {
  font-size: 12px;
}
</style>